package com.kevineric;

import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Robot;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class RobotServer implements Runnable{
	final int PORT=4055;
	Robot rob;
	
	//TODO: handle multiple screen devices
	
	public static void main(String[] args)throws Exception{
		RobotServer rs=new RobotServer();
		
		//test code
		//rs.moveMouse(100, 100);
		//rs.brownianMotion();
		//rs.circularMotion();
		
		
		rs.run();
	}
	
	public RobotServer() throws AWTException{
			rob=new Robot();

	}

	
	public void moveMouse(int dx, int dy){
		if(rob != null){
			int curx=MouseInfo.getPointerInfo().getLocation().x+dx;
			int cury=MouseInfo.getPointerInfo().getLocation().y+dy;
			if( curx<=3)
				curx=3;
			if( cury<=3)
				cury=3;
			
			rob.mouseMove(curx, cury);
		}
	}

	public boolean processCommand(String s){
		
		if(s.startsWith("m")){
			String[] parts=s.split(",");
			int dx=Integer.parseInt(parts[1]);
			int dy=Integer.parseInt(parts[2]);
			
			System.out.println("moving mouse with dx: "+dx+" dy:"+dy);
			//robot stuff
			moveMouse(dx,dy);
			
			return true;
		}
		
		return false;
	}
	
	public void run() {

		while(true){
			try{
				ServerSocket server=new ServerSocket(PORT);
				
				Socket connection=server.accept();
				System.out.println("Connection established");
				PrintStream out=new PrintStream(connection.getOutputStream());
				Scanner sc=new Scanner(connection.getInputStream());
				
				
				while(!connection.isClosed()){
					Thread.sleep(1);
					
					if(sc.hasNextLine()){
						
						processCommand(sc.nextLine());
						
					}
				}	
		
			//callback on connection failure
				server.close();
			}catch(Exception e){
				e.printStackTrace();
				return;
			}
		}
		
	}

	public void brownianMotion()throws Exception{
		while(true){
			Thread.sleep(10);
			int dx=(int)(3*Math.random())-1;
			int dy=(int)(3*Math.random())-1;
			moveMouse(dx, dy);
		}
	}
	
	public void circularMotion()throws Exception{
		double theta=0;
		double mag=5;
		
		int counter=2000;
		while(counter>0){
			Thread.sleep(10);
			theta+=Math.PI/10.0;
			int dx=(int) (Math.cos(theta)*mag);
			int dy=(int)(Math.sin(theta)*mag);
			
			moveMouse(dx, dy);
			counter--;
		}
	}
	
	
}
